<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="utf-8">
    <title>浏览页面</title>
    <link rel="stylesheet" href="/component/pear/css/pear.css"/>
    <link rel="stylesheet" href="/admin/css/reset.css"/>
</head>
<body class="pear-container">



<!-- 数据表格 -->
<div class="layui-row layui-col-space15">
    <div class="layui-col-md2">
        <div class="layui-card">
            部门列表
            <div class="layui-card-body">
                <div id="organizationTreeContent" style="overflow: auto;">
                    <ul id="organizationTree" class="dtree organizationTree" data-id="9527"></ul>
                </div>
            </div>
        </div>
    </div>
    <div class="layui-col-md10">
        <!-- 顶部查询表单 -->
        <div class="layui-card">
            <div class="layui-card-body">
                <form class="layui-form top-search-from">

<!--                    <div class="layui-form-item">-->
<!--                        <label class="layui-form-label">部门</label>-->
<!--                        <div class="layui-input-block">-->
<!--                            <div name="pid" id="pid" value="" ></div>-->
<!--                        </div>-->
<!--                    </div>-->

                    <div class="layui-form-item">
                        <label class="layui-form-label">负责人</label>
                        <div class="layui-input-block">
                            <input type="text" name="leader" value="" class="layui-input">
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">联系电话</label>
                        <div class="layui-input-block">
                            <input type="text" name="phone" value="" class="layui-input">
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">邮箱</label>
                        <div class="layui-input-block">
                            <input type="text" name="email" value="" class="layui-input">
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">部门状态</label>
                        <div class="layui-input-block">
                            <div name="status" id="status" value="" ></div>
                        </div>
                    </div>

                    <div class="layui-form-item layui-inline">
                        <label class="layui-form-label"></label>
                        <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="table-query">
                            <i class="layui-icon layui-icon-search"></i>查询
                        </button>
                        <button type="reset" class="pear-btn pear-btn-md" lay-submit lay-filter="table-reset">
                            <i class="layui-icon layui-icon-refresh"></i>重置
                        </button>
                    </div>
                    <div class="toggle-btn">
                        <a class="layui-hide">展开<i class="layui-icon layui-icon-down"></i></a>
                        <a class="layui-hide">收起<i class="layui-icon layui-icon-up"></i></a>
                    </div>
                </form>
            </div>
        </div>
        <div class="layui-card">
            <div class="layui-card-body">
                <table id="organization-table" lay-filter="organization-table"></table>
            </div>
        </div>
    </div>
</div>

<!-- 表格顶部工具栏 -->
<script type="text/html" id="table-toolbar">
    <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add" permission="admin.dept.insert">
        <i class="layui-icon layui-icon-add-1"></i>新增
    </button>
    <button class="pear-btn pear-btn-danger pear-btn-md" lay-event="batchRemove"
            permission="admin.dept.delete">
        <i class="layui-icon layui-icon-delete"></i>删除
    </button>
</script>

<!-- 表格行工具栏 -->
<script type="text/html" id="table-bar">
    {{# if(d.pid !=0){ }}
    <button class="pear-btn pear-btn-xs tool-btn" lay-event="edit" permission="admin.dept.update">编辑</button>
    <button class="pear-btn pear-btn-xs tool-btn" lay-event="remove" permission="admin.dept.delete">删除</button>
    {{# } }}
</script>

<script src="/component/layui/layui.js?v=2.8.12"></script>
<script src="/component/pear/pear.js"></script>
<script src="/admin/js/permission.js"></script>
<script src="/admin/js/common.js"></script>

<script>

    // 相关常量
    const PRIMARY_KEY = "id";
    const SELECT_API = "/admin/dept/select";
    const SELECT_TREE_API = "/admin/dept/select_tree";
    const UPDATE_API = "/admin/dept/update";
    const DELETE_API = "/admin/dept/delete";
    const INSERT_URL = "/admin/dept/insert";
    const UPDATE_URL = "/admin/dept/update";
    // 字段 父部门id pid
    layui.use(["jquery", "xmSelect", "popup"], function() {
        layui.$.ajax({
            url: "/admin/dept/select?format=tree",
            dataType: "json",
            success: function (res) {
                let value = layui.$("#pid").attr("value");
                let initValue = value ? value.split(",") : [];
                layui.xmSelect.render({
                    el: "#pid",
                    name: "pid",
                    initValue: initValue,
                    filterable: true,
                    data: res.data,
                    model: {"icon":"hidden","label":{"type":"text"}},
                    clickClose: true,
                    radio: true,
                    tree: {show:true,strict:false,clickCheck:true,clickExpand:false,expandedKeys:initValue},
                });
                if (res.code) {
                    layui.popup.failure(res.msg);
                }
            }
        });
    });
    // 字段 部门状态（0.停用 1.正常） status
    layui.use(["jquery", "xmSelect"], function() {
        let value = layui.$("#status").attr("value");
        let initValue = value ? value.split(",") : [];
        layui.xmSelect.render({
            el: "#status",
            name: "status",
            filterable: true,
            initValue: initValue,
            data: [{"value":"0","name":"开启"},{"value":"1","name":"关闭"}],
            model: {"icon":"hidden","label":{"type":"text"}},
            clickClose: true,
            radio: true,
        })
    });
    // 表格渲染
    layui.use(["table", "form", "common", "popup", "util", "dtree","drawer"], function () {
        let table = layui.table;
        let form = layui.form;
        let $ = layui.$;
        let common = layui.common;
        let util = layui.util;
        let dtree = layui.dtree;
        let drawer = layui.drawer;
        // 表头参数
        let cols = [
            {
                type: "checkbox",
                align: "center"
            },{
                title: "ID",align: "center",
                field: "id",
            },{
                title: "上级部门",align: "center",
                field: "pid",
                templet: function (d) {
                    let field = "pid";
                    if (typeof d[field] == "undefined") return "";
                    let items = [];
                    layui.each((d[field] + "").split(","), function (k , v) {
                        items.push(apiResults[field][v] || v);
                    });
                    if (d.pid==0) return '';
                    return util.escape(items.join(","));
                }
            },{
                title: "祖级列表",align: "center",
                field: "ancestors",
                hide: true,
            },{
                title: "部门名称",align: "center",
                field: "name",
            },{
                title: "显示顺序",align: "center",
                field: "order_num",
                sort: true,
            },{
                title: "负责人",align: "center",
                field: "leader",
            },{
                title: "联系电话",align: "center",
                field: "phone",
                sort: true,
            },{
                title: "邮箱",align: "center",
                field: "email",
            },{
                title: "部门状态",align: "center",
                field: "status",
                sort: true,
                templet: function (d) {
                    let field = "status";
                    form.on("switch("+field+")", function (data) {
                        let load = layer.load();
                        let postData = {};
                        postData[field] = data.elem.checked ? 1 : 0;
                        postData[PRIMARY_KEY] = this.value;
                        $.post(UPDATE_API, postData, function (res) {
                            layer.close(load);
                            if (res.code) {
                                return layui.popup.failure(res.msg, function () {
                                    data.elem.checked = !data.elem.checked;
                                    form.render();
                                });
                            }
                            return layui.popup.success("操作成功");
                        })
                    });
                    let checked = d[field] == 0 ? "checked" : "";
                    if (d.pid === 0) return '';
                    //if (d.LAY_INDEX === 0) return '';
                    return '<input type="checkbox" value="'+util.escape(d[PRIMARY_KEY])+'" lay-filter="'+util.escape(field)+'" lay-skin="switch" lay-text="'+util.escape('开启|关闭')+'" '+checked+'/>';
                }
            },{
                title: "删除标志",align: "center",
                field: "del_flag",
                hide: true,
            },{
                title: "创建者",align: "center",
                field: "created_by",
            },{
                title: "创建时间",align: "center",
                field: "created_at",
            },{
                title: "更新者",align: "center",
                field: "updated_by",hide: true,
            },{
                title: "更新时间",align: "center",
                field: "updated_at",hide: true,
            },{
                title: "操作",
                toolbar: "#table-bar",
                align: "center",
                fixed: "right",
                width: 200,
            }
        ];
        const DTree = dtree.render({
            elem: "#organizationTree",
            //data: organizationTree,
            initLevel: "5", //默认展开层级为1
            line: true, // 有线树
            ficon: ["1", "-1"], // 设定一级图标样式。0表示方形加减图标，8表示小圆点图标 一级图标非叶子节点： 0：文件夹，1：方形加减，2：三角形，-1：不显示一级图标非叶子节点一级图标叶子节点：0：文件夹，1：人员，2：机构，3：报表，4：信息，5：叶子，6：勋章，7：文件，8：小圆点，9：齿轮，10：星星， -1：不显示一级图标叶子节点。
            icon: ["0", "2"], // 设定二级图标样式。0表示文件夹图标，5表示叶子图标 二级图标非叶子节点：0：文件夹，1：方形加减，2：三角形，-1：不显示二级图标非叶子节点二级图标叶子节点：0：文件夹，1：人员，2：机构，3：报表，4：信息，5：叶子，6：勋章，7：文件，8：小圆点，9：齿轮，10：星星， -1：不显示二级图标叶子节点。
            method: 'get',
            formatter: {
                title: function(data) {  // 示例给有子集的节点返回节点统计
                    let s = data.title;
                    if (data.children){
                        s += ' <span style=\'color:blue\'>(' + data.children.length + ')</span>';
                    }
                    return s;
                }
            },
            width: "100%",
            //accordion: true,  // 开启手风琴
            height: "full-150",  // 设置高度，也可以直接固定数字
            none: "暂无数据",
            url: SELECT_TREE_API
        });

        // 渲染表格
        function render() {
            table.render({
                elem: "#organization-table",
                url: SELECT_API,
                page: true,
                cols: [cols],
                skin: "line",
                size: "lg",
                toolbar: "#table-toolbar",
                autoSort: false,
                defaultToolbar: [{
                    title: "刷新",
                    layEvent: "refresh",
                    icon: "layui-icon-refresh",
                }, "filter", "print", "exports"],
                done: function () {
                    layer.photos({photos: 'div[lay-id="organization-table"]', anim: 5});
                }
            });
        }
        let nodeId;
        // 绑定节点点击事件
        dtree.on("node(organizationTree)", function (obj) {
            const name_like = $('#name_like').val();
            //绑定右侧数据
            nodeId = obj.param.nodeId;
            const parentId = obj.param.parentId;
            let pr_url;
            if (parentId == -1) {
                pr_url = SELECT_API;
            } else {
                pr_url = SELECT_API + "?pid=" + nodeId;
            }
            if (name_like !="" && name_like!=undefined){
                pr_url = pr_url+"&name[0]=like&name[1]="+name_like;
            }
            //点击图标才能收缩收缩和展开,放开就是点击整行就能点击收缩和展开
            if (!obj.param.leaf) {
                //const $div = obj.dom;
                //DTree.clickSpread($div); //调用内置函数展开节点
            }
            table.render({
                elem: "#organization-table",
                url: pr_url,
                page: true,
                cols: [cols],
                skin: "line",
                size: "lg",
                toolbar: "#table-toolbar",
                autoSort: false,
                defaultToolbar: [{
                    title: "刷新",
                    layEvent: "refresh",
                    icon: "layui-icon-refresh",
                }, "filter", "print", "exports"],
                done: function () {
                    layer.photos({photos: 'div[lay-id="organization-table"]', anim: 5});
                }
            });

        });

        // 获取表格中下拉或树形组件数据
        let apis = [];
        apis.push(["pid", "/admin/dept/select?format=select&limit=1000"]);
        let apiResults = {};
        apiResults["pid"] = [];
        let count = apis.length;
        layui.each(apis, function (k, item) {
            let [field, url] = item;
            $.ajax({
                url: url,
                dateType: "json",
                success: function (res) {
                    if (res.code) {
                        return layui.popup.failure(res.msg);
                    }

                    function travel(items) {
                        for (let k in items) {
                            let item = items[k];
                            apiResults[field][item.value] = item.name;
                            if (item.children) {
                                travel(item.children);
                            }
                        }
                    }

                    travel(res.data);
                },
                complete: function () {
                    if (--count === 0) {
                        render();
                    }
                }
            });
        });
        if (!count) {
            render();
        }

        // 编辑或删除行事件
        table.on("tool(organization-table)", function (obj) {
            if (obj.event === "remove") {
                remove(obj);
            } else if (obj.event === "edit") {
                edit(obj);
            }
        });

        // 表格顶部工具栏事件
        table.on("toolbar(organization-table)", function (obj) {
            if (obj.event === "add") {
                add();
            } else if (obj.event === "refresh") {
                refreshTable();
            } else if (obj.event === "batchRemove") {
                batchRemove(obj);
            }
        });

        // 表格顶部搜索事件
        form.on("submit(table-query)", function (data) {
            if (nodeId){
                data.field.pid=nodeId;
            }
            table.reload("organization-table", {
                page: {
                    curr: 1
                },
                where: data.field
            })
            return false;
        });

        // 表格顶部搜索重置事件
        form.on("submit(table-reset)", function (data) {

            table.reload("organization-table", {
                where:[]
            })
        });

        // 字段允许为空
        form.verify({
            phone: [/(^$)|^1\d{10}$/, "请输入正确的手机号"],
            email: [/(^$)|^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/, "邮箱格式不正确"],
            url: [/(^$)|(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/, "链接格式不正确"],
            number: [/(^$)|^\d+$/, '只能填写数字'],
            date: [/(^$)|^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/, "日期格式不正确"],
            identity: [/(^$)|(^\d{15}$)|(^\d{17}(x|X|\d)$)/, "请输入正确的身份证号"]
        });

        // 表格排序事件
        table.on("sort(organization-table)", function (obj) {
            table.reload("organization-table", {
                initSort: obj,
                scrollPos: "fixed",
                where: {
                    field: obj.field,
                    order: obj.type
                }
            });
        });

        // 表格新增数据
        let add = function () {
            drawer.open({
                legacy: false,
                title: ['新增', 'font-size:16px;color:#2d8cf0'],
                offset: 'r',
                area: "50%",
                maxmin: true,
                closeBtn: 1,
                iframe: INSERT_URL+"?pid="+nodeId,
            });
        }

        // 表格编辑数据
        let edit = function (obj) {
            let value = obj.data[PRIMARY_KEY];
            drawer.open({
                legacy: false,
                title: ['修改', 'font-size:16px;color:#2d8cf0'],
                offset: 'r',
                area: "50%",
                maxmin: true,
                closeBtn: 1,
                iframe: UPDATE_URL + "?" + PRIMARY_KEY + "=" + value,
            });
        }

        // 删除一行
        let remove = function (obj) {
            return doRemove(obj.data[PRIMARY_KEY]);
        }

        // 删除多行
        let batchRemove = function (obj) {
            let checkIds = common.checkField(obj, PRIMARY_KEY);
            if (checkIds === "") {
                layui.popup.warning("未选中数据");
                return false;
            }
            doRemove(checkIds.split(","));
        }

        // 执行删除
        let doRemove = function (ids) {
            let data = {};
            data[PRIMARY_KEY] = ids;
            layer.confirm("确定删除?", {
                icon: 3,
                title: "提示"
            }, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: DELETE_API,
                    data: data,
                    dataType: "json",
                    type: "post",
                    success: function (res) {
                        layer.close(loading);
                        if (res.code) {
                            return layui.popup.failure(res.msg);
                        }
                        return layui.popup.success("操作成功", refreshTable);
                    }
                })
            });
        }

        // 刷新表格数据
        window.refreshTable = function () {
            table.reloadData("organization-table", {
                scrollPos: "fixed",
                done: function (res, curr) {
                    if (curr > 1 && res.data && !res.data.length) {
                        curr = curr - 1;
                        table.reloadData("organization-table", {
                            page: {
                                curr: curr
                            },
                        })
                    }
                }
            });
            table.reloadData("organizationTree", {
                scrollPos: "fixed",
                done: function (res, curr) {
                    if (curr > 1 && res.data && !res.data.length) {
                        curr = curr - 1;
                        table.reloadData("organizationTree", {
                            page: {
                                curr: curr
                            },
                        })
                    }
                }
            });
        }
    })

</script>
</body>
</html>
